import { Sequelize, DataTypes } from 'sequelize';
import initializeDataBase from '@src/db/db';

import UserModel from './User';
import GroupModel from './Group';

const MessageModel = async () => {
    const sequelize: Sequelize = await initializeDataBase();
    const Message = sequelize.define('message', {
        id: {
            type: DataTypes.INTEGER,
            autoIncrement: true,
            primaryKey: true
        },
        send_id: {
            type: DataTypes.INTEGER,
            allowNull: false,
            references: {
                model: 'user',
                key: 'id'
            }
        },
        // 私聊时使用
        receive_id: {
            type: DataTypes.INTEGER,
            allowNull: true,
            references: {
                model: 'user',
                key: 'id'
            }
        },
        // 群聊时使用
        group_id: {
            type: DataTypes.INTEGER,
            allowNull: true,
            references: {
                model: 'group',
                key: 'id'
            }
        },
        content: {
            type: DataTypes.STRING,
            allowNull: false
        },
        type: {
            type: DataTypes.ENUM('text', 'image', 'file', 'video', 'voice'),
            allowNull: false
        },
        status: {
            type: DataTypes.ENUM('sent', 'read', 'delivered'),
            allowNull: false
        }
    })

    const User = await UserModel();
    const Group = await GroupModel();

    Message.belongsTo(User, { foreignKey: 'send_id' });
    Message.belongsTo(User, { foreignKey: 'receive_id' });
    Message.belongsTo(Group, { foreignKey: 'group_id' });

    await sequelize.sync({ alter: true });
    return sequelize.models.message;
}

export default MessageModel;